<template>
  <div class="list">
    <a-form
        ref="searchFormRef"
        class="search-form base-mb15"
        :label-col="{ style: { minWidth: '100px' } }"
        :model="searchFormState"
        @finish="onSearchFinish"
    >
      <a-row :gutter="[10, 24]">
        <a-col :span="6">
          <a-form-item name="userName" label="Customer Name">
            <a-input v-model:value="searchFormState.userName"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="6">
          <a-form-item name="mobile" :label="$t('self.order.tips2')">
            <a-input v-model:value="searchFormState.mobile"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="orderNo" :label="$t('self.order.tips13')">
            <a-input v-model:value="searchFormState.orderNo"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="orgId" :label="$t('self.order.tips12')">
            <a-select v-model:value="searchFormState.orgId" :options="searchOrgOptions" :fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"/>
          </a-form-item>
        </a-col>

        <a-col :span="6">
          <a-form-item name="vehicle" :label="$t('self.stationMap.vehicleType')">
            <a-select v-model:value="searchFormState.vehicle" :options="vehicleTypeOptions" :fieldNames="{label: 'label',value: 'value'}" :placeholder="$t('self.pleaseChoose')"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="gunType" label="ChargeType">
            <a-select v-model:value="searchFormState.gunType" :options="chargeTypeOptions" :fieldNames="{label: 'label',value: 'value'}" :placeholder="$t('self.pleaseChoose')"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="startTime" :label="$t('self.order.tips14')">
            <a-date-picker v-model:value="searchFormState.startTime" style="width: 100%;"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="endTime" :label="$t('self.order.tips15')">
            <a-date-picker v-model:value="searchFormState.endTime" style="width: 100%;"/>
          </a-form-item>
        </a-col>
        <a-col :span="6" offset="1" class="base-flex base-rows">
          <a-button type="primary" html-type="submit">{{ $t('self.searchButton') }}</a-button>
          <a-button class="base-ml10" @click="resetSearchForm">{{ $t('self.resetButton') }}</a-button>
        </a-col>
      </a-row>
    </a-form>

    <s-table ref="stableRef" :api-obj="tableConfig.apiObj" api-method="POST" 
    :columns="sourceColumn" row-key="id" :light-index="tableConfig.lightIndex" 
    :params="{ status: searchFormState.status}" :is-row-selection="false"
    @selectionChange="tableSelectionChange" :is-show-tool="false" :scroll="{ x: 2500 }">
      <template #bodyCell="{ column, record, index }">
        <!--帐户状态-->
        <template v-if="column.key === 'status'">
          <template v-if="record[column.key]">
            <sc-status-indicator type="primary"></sc-status-indicator>
            {{ $t('self.user.tips6') }}
          </template>
          <template v-else>
            <sc-status-indicator type="warning"></sc-status-indicator>
            {{ $t('self.user.tips7') }}
          </template>
        </template>

        <template v-if="column.key === 'action'">
            <span>
              <a href="javascript:void(0)" @click="openDetailModal(record, index)">{{ $t('self.detailView') }}</a>
            </span>
        </template>

      </template>
    </s-table>

    <detailModal ref="detailModalRef" @ok="" @close=""></detailModal>

  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref, watch } from 'vue'
import detailModal from './detail_modal.vue'
import { useRoute, useRouter } from 'vue-router'
import ScStatusIndicator from '@/components/scMini/scStatusIndicator.vue'
import { mainStore } from '@/stores/mainStore'

const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const route = useRoute()
const router = useRouter()
const useMainStore = mainStore()

const selectedKey = ref([])
const stableRef = ref(null)
const tableConfig = ref({
  apiObj: $API.backend.order.list,
  lightIndex: [] // 要高亮的行号
})
// 表格列
const sourceColumn = ref([])

onMounted(async () => {
  // 获取表格列
  resetDefaultOptionsByLang()
  // 获取运营商下拉数据
  searchOrgOptions.value = await proxy.getOrgSelectList(true)
})

// 监听 lang 状态
watch(
    () => useMainStore.lang, // 切换语言包时
    (curr, old) => {
      // console.log('语言包', curr)
      // 获取表格列
      resetDefaultOptionsByLang()
    }
)
	const vehicleTypeOptions = ref([
		{ label: 'E-Car', value: 'car' },
		{ label: 'E-Motorcycle', value: 'moto' }
	]);
  const chargeTypeOptions = ref([
		{ label: 'DC', value: 2 },
		{ label: 'AC', value: 1 }
	]);
const resetDefaultOptionsByLang = () => {
  sourceColumn.value = [
    {
      title: $T('self.order.tips210'),
      dataIndex: 'orderNo',
      key: 'orderNo'
      // width: 110
    },
    {
      title: $T('self.order.tips211'),
      dataIndex: 'userName',
      key: 'userName'
		},
    {
      title: $T('self.stationMap.tips77'),
      dataIndex: 'orgName',
      key: 'orgName'
		},
    {
      title: 'CITY | COUNTRY',
      dataIndex: 'city',
      key: 'city',
      customRender: ({record}) => {
			  return (record.city + '-' + record.country);
		  },
    },
    {
      title: $T('self.order.tips204'),
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: $T('self.order.tips202'),
      dataIndex: 'cardNo',
      key: 'cardNo',
      width: 150
		},
    {
      title: $T('self.order.tips205'),
      dataIndex: 'createTime',
      key: 'createTime'
    },
    // {
    //   title: $T('self.order.tips207'),
    //   dataIndex: 'stationName',
    //   key: 'stationName'
		// },
    {
        title: $T('self.order.tips212'),
        dataIndex: 'stationId',
        key: 'stationId'
		},
    {
      title: $T('self.order.tips213'),
      dataIndex: 'gunNo',
      key: 'gunNo',
      customRender: ({text}) => {
        return (text == 1 ? "A":"B");
      },
		},
    {
      title: $T('self.businessStation.modal.col15'),
      dataIndex: 'vehicle',
      key: 'vehicle',
      customRender: ({text}) => {
        return (text == 1 ? "E-CARS":"MOTOS");
      },
		},
    // {
    //   title: $T('self.order.tips5'),
    //   dataIndex: 'pileNo',
    //   key: 'pileNo'
    // },
    {
      title: $T('self.order.tips207'),
      dataIndex: 'stationName',
      key: 'stationName'
    },
    {
      title: $T('self.order.tips208'),
      dataIndex: 'currentV',
      key: 'currentV'
    },
    {
      title: $T('self.order.tips209'),
      dataIndex: 'currentA',
      key: 'currentA'
    },
    {
      title: $T('self.order.tips203'),
      dataIndex: 'totalChargeQuantity',
      key: 'totalChargeQuantity',
      // 自定义显示列
      customRender: ({text, record}) => {
        // 将 text 转换为数值类型
        const numericValue = parseFloat(text);
        if (isNaN(numericValue)) return ''; // 如果不是有效的数值，则返回空字符串
        // 除以1000并保留最多2位小数
        return (numericValue / 1000).toFixed(2);
      },
    },
    {
      title: $T('self.order.tips214'),
      dataIndex: 'totalChargeTimes',
      key: 'totalChargeTimes',
      // 自定义显示列
      customRender: ({text, record}) => {
        // 接口返回是秒，处理为分
        return proxy.getMinBySeconds(text)
      },
    },
    {
      title: $T('self.order.tips215'),
      dataIndex: 'totalChargeMoney',
      key: 'totalChargeMoney'
    },
    {
      title: $T('self.userCharge.tips15'),
      dataIndex: 'keyfob',
      key: 'keyfob'
    },
    { title: $T('self.actionButton'), key: 'action', ellipsis: true, fixed: 'right', width: 100 }
  ]
  searchOrderTypeOptions.value = [
    {
      label: $T('self.order.orderType.all'),
      value: ''
    },
    {
      label: $T('self.order.orderType.tips1'),
      value: 1
    },
    {
      label: $T('self.order.orderType.tips2'),
      value: 2
    },
    {
      label: $T('self.order.orderType.tips3'),
      value: 3
    },
    {
      label: $T('self.order.orderType.tips4'),
      value: 4
    },
    {
      label: $T('self.order.orderType.tips5'),
      value: 5
    }
  ]
  // 充电中：2
  // 充电结束（待结算）：3
  // 已结算：4
  // 已结束（非正常充电结束）5
  // 历史订单：1
  searchStatusOptions.value = [
    {
      label: $T('self.order.statusType.all'),
      value: ''
    },
    {
      label: $T('self.order.statusType.tips1'),
      value: 3
    },
    {
      label: $T('self.order.statusType.tips2'),
      value: 4
    },
    {
      label: $T('self.order.statusType.tips3'),
      value: 5
    },
    {
      label: $T('self.order.statusType.tips4'),
      value: 1
    },
  ]
}

const tableSelectionChange = (rows, record) => {
  selectedKey.value = rows
  // console.log('表格选择项', rows, record)
}

// =========start search表单
const searchFormRef = ref(null)
// 参数status:
// 充电结束（待结算）：3
// 已结算：4
// 已结束（非正常充电结束）5（包含充电中）
// 历史订单：1
const searchFormState = ref({
  mobile: '',
  orderNo: '', 
  orgId: null, 
  stationId: '', 
  startTime: '', 
  endTime: '', 
  status: 4, 
  userName: '', 
  vehicle: '', 
  gunType: '', 
})
const searchOrgOptions = ref([])
const searchOrderTypeOptions = ref([])
const searchStatusOptions = ref([])
const onSearchFinish = (values) => {
  values.orgId = values.orgId?values.orgId: ''
  stableRef.value.upData(values, 1)
}
// 重置搜索表单
const resetSearchForm = () => {
  searchFormRef.value.resetFields()
}
// =========end search表单

const detailModalRef = ref(null)
const openDetailModal = (record, index) => {
  tableConfig.value.lightIndex = [index] // 仅高亮当前行
  nextTick(() => {
    detailModalRef.value.show(record)
  })
}


</script>

<style lang="scss" scoped>
.list {
  height: 100%;
  background: #ffffff;
  padding: 15px;

  .search-form {
    padding: 16px;
    background: rgb(247, 248, 250);

    :deep(.ant-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>
